﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace Himp.Outpatient
{
    /// <summary>
    /// 门诊处方明细
    /// </summary>
    public class OtpRxRecDetlService : OutpatientAppService, IOtpRxRecDetlService
    {
        private IRepository<OtpRxRecDetl, Guid> _otpRxRecDetlRepository;
        private IOtpRxOrdService _otpRxOrdService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="otpMdtrtRecRepository"></param>
        public OtpRxRecDetlService(IRepository<OtpRxRecDetl, Guid> otpRxRecDetlRepository
            , IOtpRxOrdService otpRxOrdService)
        {
            _otpRxRecDetlRepository = otpRxRecDetlRepository;
            _otpRxOrdService = otpRxOrdService;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<OtpRxRecDetlDto>> GetListAsync(OtpRxRecDetlInput input)
        {
            var iQuery = await _otpRxRecDetlRepository.GetQueryableAsync();

            if (!string.IsNullOrEmpty(input.Invono))
            {
                var otpRxOrds = await _otpRxOrdService.GetListAsync(new OtpRxOrdInput() { Invono = input.Invono });
                iQuery = iQuery.Where(i => otpRxOrds.Items.Select(o=>o.OtpRxRecDetlId).Contains(i.Id));
            }

            if (input.Pi == 0)
            {
                var itemsDto = ObjectMapper.Map<List<OtpRxRecDetl>, List<OtpRxRecDetlDto>>(iQuery.ToList());

                return new PagedResultDto<OtpRxRecDetlDto>(itemsDto.Count, itemsDto);
            }
            else
            {
                var totalCount = iQuery.Count();
                var items = iQuery.Page(input.Pi, input.Ps);
                var itemsDto = ObjectMapper.Map<List<OtpRxRecDetl>, List<OtpRxRecDetlDto>>(items.ToList());

                return new PagedResultDto<OtpRxRecDetlDto>(totalCount, itemsDto);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<OtpRxRecDetlDto> PostAsync(OtpRxRecDetlCreateDto input)
        {
            var otpRxRex = ObjectMapper.Map<OtpRxRecDetlCreateDto, OtpRxRecDetl>(input);
            otpRxRex = await _otpRxRecDetlRepository.InsertAsync(otpRxRex);
            var itemDto = ObjectMapper.Map<OtpRxRecDetl, OtpRxRecDetlDto>(otpRxRex);

            return itemDto;
        }
    }
}
